<?php

namespace App\Http\Utils;
/**
 * 支付工具类
 * 文档：https://pay.yansongda.cn/docs/v3/quick-start/init.html
 */
use Yansongda\Pay\Pay;

class PayUtil
{
    /**
     * @param string $pay_no 支付单号
     * @param float $money 支付金额（元）
     * @param string $openid OPENID
     * @param string $notify_url 支付回调通知地址
     * @param string $body 购买内容说明
     * @param string $channel 支付渠道，mini-小程序，app-APP，mp-公众号，scan-扫码，wap-手机网站
     * @param array|null $extra
     * @return \Illuminate\Http\JsonResponse
     */
    public static function wxpay(string $pay_no,float $money,string $openid=null,string $notify_url='/api/notify',string $body='购买商品',string $channel="mini",?array $extra=null){

        $data = [
            'out_trade_no' =>$pay_no,
            'description' => $body,
            'notify_url'=>stripos($notify_url,"HTTP")===0?$notify_url:env('APP_URL').$notify_url,
            'amount' => [
                'total' => intval( $money*100),
                'currency' => 'CNY',
            ]
        ];
        if($channel=='mini'||$channel=='mp'){
            if(config('pay.wechat.default.mode')==Pay::MODE_SERVICE){//服务商模式
                $data['payer']=[
                    'sub_openid' => $openid,
                ];

            }else{
                $data['payer']=[
                    'openid' => $openid,
                ];
            }
        }

        if(!empty($extra)){
            $data=array_merge($data,$extra);
        }
        try{
            $res=Pay::wechat(config("pay"))->$channel($data);
            return $res;
        }catch(\Exception $e){
            return self::getError($e);
        }
    }

    /**
     * 退款状态查询
     * @param string $pay_no
     */
    public static function wxpayRefundQuery(string $pay_no){
        $res=Pay::wechat(config("pay"))->find([]);
    }
    /**
     * @param float $money 退款金额（元）
     * @param float $money_total 原订单金额
     * @param string $pay_no 原支付订单号
     * @param string|null $refund_no 退款单号
     * @return bool|mixed
     */
    public static function wxpayRefund(float $money,float $money_total,string $pay_no,?string $refund_no=null){
        if(empty($refund_no))$refund_no=unique_no("TK");

        $order = [
            'out_trade_no' => $pay_no,
            'out_refund_no' => $refund_no??"TK".$pay_no.rand_char(4,3),
            'amount' => [
                'refund' => intval($money*100),
                'total' =>intval($money_total*100),
                'currency' => 'CNY',
            ],
        ];
        try{
            $res = Pay::wechat(config("pay"))->refund($order);
            $res = json_decode(json_encode($res),true);
            if(isset($res['status'])&&($res['status']=="SUCCESS"||$res['status']=='PROCESSING')){
                return true;
            }else if(isset($res['message'])){
                return $res['message'];
            }else{
                return "取消失败";
            }
        }catch(\Exception $e){
            return self::getError($e);
        }

    }



    /**
     * @param string $order_no 流水号
     * @param float $money 提现金额（元）
     * @param string $openid OPENID
     * @param string $description 描述
     * @param string|null $true_name 真实姓名
     * @return mixed
     */
    public static function wxpayTransfer(string $order_no,float $money,string $openid,string $description="提现",string $true_name=null){
        $order = [
            'out_batch_no' => $order_no,
            'batch_name' =>$description,
            'batch_remark' =>$description,
            'total_amount' =>intval($money*100),
            'total_num' => 1,
            'transfer_detail_list' => [
                [
                    'out_detail_no' =>$order_no,
                    'transfer_amount' => intval($money*100),
                    'transfer_remark' => $description,
                    'openid' => $openid,
                    // 'user_name' => ''  // 明文传参即可，sdk 会自动加密
                ],
            ],
        ];
        if(!empty($true_name)){
            $order['transfer_detail_list'][0]['user_name']=$true_name;
        }
        try{
            $res= Pay::wechat(config("pay"))->transfer($order);

            $res = json_decode(json_encode($res),true);
            if(isset($res['status'])&&($res['status']=="SUCCESS"||$res['status']=='PROCESSING')){
                return true;
            }else if(isset($res['message'])){
                return $res['message'];
            }else{
                return "转账失败";
            }
        }catch(\Exception $e){
            return self::getError($e);
        }
    }
    public static function getError($err){
        $str=$err->getMessage();
        $arr= json_decode(json_encode($err,JSON_UNESCAPED_UNICODE),true);
        if(isset($arr['response'])){
            if(isset($arr['response']['body'])&&gettype($arr['response']['body'])=='string'){
                preg_match('/message\":\"(.*?)\"\}/',$arr['response']['body'],$arr);
                if(isset($arr[1]))return ['message'=>$arr[1]];
            }
            return $arr['response'];
        }else{
            return  $err->getMessage();
        }
    }
}
